#include "Triangle.h"
#include "VertexTypes.h"

Triangle::Triangle(ID3D10Device* pDevice)
{
	pEffect = NULL;
	pTechnique = NULL;
	pVertexLayout = NULL;
	pVertexBuffer = NULL;

	this->pDevice = pDevice;
}

Triangle::~Triangle(void)
{
	if (pVertexBuffer != NULL) pVertexBuffer->Release();
	if (pVertexLayout != NULL) pVertexLayout->Release();
	if (pEffect != NULL) pEffect->Release();
}

HRESULT Triangle::Initialize()
{
	HRESULT hr;

	hr = InitializeEffect();
	if (FAILED(hr)) return hr;

	hr = InitializeVertexLayout();
	if (FAILED(hr)) return hr;

	hr = InitializeVertexBuffer();
	if (FAILED(hr)) return hr;
	
	return S_OK;
}

HRESULT Triangle::InitializeVertexLayout()
{
	HRESULT hr;

	D3D10_PASS_DESC PassDesc;
	pTechnique->GetPassByIndex(0)->GetDesc(&PassDesc);
	hr = pDevice->CreateInputLayout(PositionVertexLayout, PositionVertexNumElements, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &pVertexLayout);
	if (FAILED(hr)) return hr;

	return S_OK;
}

HRESULT Triangle::InitializeVertexBuffer()
{
	HRESULT hr;

	PositionVertex vertices[] =
	{
		D3DXVECTOR3(0.0f, 0.5f, 0.5f),
		D3DXVECTOR3(0.5f, -0.5f, 0.5f),
		D3DXVECTOR3(-0.5f, -0.5f, 0.5f),
	};
	
	D3D10_BUFFER_DESC bd;
	bd.Usage = D3D10_USAGE_DEFAULT;
	bd.ByteWidth = sizeof(PositionVertex)*3;
	bd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
	bd.CPUAccessFlags = 0;
	bd.MiscFlags = 0;

	D3D10_SUBRESOURCE_DATA InitData;
	InitData.pSysMem = vertices;

	hr = pDevice->CreateBuffer(&bd, &InitData, &pVertexBuffer);
	if (FAILED(hr)) return hr;

	this->stride = sizeof(PositionVertex);
	this->offset = 0;
	
	return S_OK;
}

HRESULT Triangle::InitializeEffect()
{
	HRESULT hr;

	hr = D3DX10CreateEffectFromFile(L"Triangle.fx", NULL, NULL, "fx_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, pDevice, NULL, NULL, &pEffect, NULL, NULL);
	if (FAILED(hr)) return hr;

	pTechnique = pEffect->GetTechniqueByName("Render");

	return S_OK;
}

void Triangle::Render()
{
	pDevice->IASetInputLayout(pVertexLayout);
	pDevice->IASetVertexBuffers(0, 1, &pVertexBuffer, &stride, &offset);
	pDevice->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

	D3D10_TECHNIQUE_DESC techDesc;
	pTechnique->GetDesc(&techDesc);
	for (UINT p = 0; p < techDesc.Passes; ++p)
	{
		pTechnique->GetPassByIndex(p)->Apply(0);
		pDevice->Draw(3,0);
	}
}